package zheezes.util;

import java.util.Calendar;
import java.util.Date;

public class DateUtil {
	public static final long compare(Calendar ca, Calendar cb, int field) {
		long ma = ca.getTimeInMillis() + ca.getTimeZone().getRawOffset();
		long mb = cb.getTimeInMillis() + cb.getTimeZone().getRawOffset();

		switch (field) {
		case Calendar.MILLISECOND:
			return ma - mb;
		case Calendar.SECOND:
			return (ma / 1000) - (mb / 1000);
		case Calendar.MINUTE:
			return (ma / (1000 * 60)) - (mb / (1000 * 60));
		case Calendar.HOUR_OF_DAY:
			return (ma / (1000 * 60 * 60)) - (mb / (1000 * 60 * 60));
		case Calendar.DATE:
			return (ma / (1000 * 60 * 60 * 24)) - (mb / (1000 * 60 * 60 * 24));
		case Calendar.MONTH:
			return (ca.get(Calendar.YEAR) - cb.get(Calendar.YEAR)) * 12
					+ (ca.get(Calendar.MONTH) - ca.get(Calendar.MONTH));
		case Calendar.YEAR:
			return ca.get(Calendar.YEAR) - cb.get(Calendar.YEAR);
		default:
			return Long.MAX_VALUE;
		}
	}

	public static final long compare(Date da, Date db, int field) {
		Calendar ca = Calendar.getInstance();
		ca.setTime(da);
		Calendar cb = Calendar.getInstance();
		cb.setTime(db);
		return compare(ca, cb, field);
	}
	
	public static final void cutoff(Calendar cal, int field, boolean inc) {
		int[] fields = new int[] { Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND };
		for (int i = 0, n = fields.length; i < n; i++) {
			int f = fields[i];
			if((field == f && inc) || field < f) {
				cal.set(f, 0);
			}
		}
	}
	
	public static final void cutoff(Date date, int field, boolean inc) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cutoff(cal, field, inc);
		date.setTime(cal.getTimeInMillis());
	}
}
